// import postcsspxtoviewport from "postcss-px-to-viewport";
import { loadEnv, type ConfigEnv, type UserConfigExport } from "vite";
import { exclude, include } from "./build/optimize";
import { getPluginsList } from "./build/plugins";
import { __APP_INFO__, alias, pathResolve, root, warpperEnv } from "./build/utils";

// import postcssConfig from "./postcss.config.js";
const times = new Date().getTime();

export default ({ mode }: ConfigEnv): UserConfigExport => {
  const {
    VITE_PORT,
    VITE_COMPRESSION,
    VITE_PUBLIC_PATH,
    VITE_API_URL,
    VITE_SERVE_API_URL,
    VITE_SERVE_API_URL_WS,
    VITE_FANRUAN_BASE_URL,
    VITE_SERVE_API_STATIC_URL
  } = warpperEnv(loadEnv(mode, root));
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias
    },
    // css: {
    //   postcss: {
    //     plugins: [
    //       ...postcssConfig,
    //       postcsspxtoviewport({
    //         unitToConvert: "rpx",
    //         viewportWidth: 900, // 设计稿宽度（如 1920px 大屏）
    //         viewportHeight: 900, // 设计稿高度（转 vh 需配置）
    //         viewportUnit: "vh", // 目标单位（支持 vh）
    //         fontViewportUnit: "vh", // 字体单位
    //         selectorBlackList: ["mb-"], // 忽略类名
    //         minPixelValue: 1, // 最小转换值
    //         include: "/src\/views\/all\/screen/"
    //       })
    //     ]
    //   }
    // },
    // 服务端渲染
    server: {
      // 端口号
      port: VITE_PORT,
      host: "0.0.0.0",
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      open: true,
      cors: true,
      // 跨域代理配置
      proxy: {
        "/ifp-web-static/": {
          target: VITE_SERVE_API_STATIC_URL,
          changeOrigin: true,
          bypass(req, res, options) {
            const proxyURL = options.target + "";
            res.setHeader("x-req-proxyURL", proxyURL); // 将真实请求地址设置到响应头中
          }
        },
        "/wss": {
          target: VITE_SERVE_API_URL_WS,
          changeOrigin: true,
          ws: true
        },
        "/api": {
          target: VITE_SERVE_API_URL,
          changeOrigin: true,
          rewrite: path => path.replace(VITE_API_URL, "")
        },
        [VITE_API_URL]: {
          target: VITE_SERVE_API_URL,
          changeOrigin: true,
          rewrite: path => path.replace(VITE_API_URL, "")
        },
        ["/fineReport"]: {
          target: VITE_FANRUAN_BASE_URL,
          changeOrigin: true,
          rewrite: path => path.replace("/fineReport", "")
        }
      },

      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ["./index.html", "./src/{views,components}/*"]
      }
    },
    plugins: getPluginsList(VITE_COMPRESSION),
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      include,
      exclude
    },
    build: {
      // https://cn.vitejs.dev/guide/build.html#browser-compatibility
      target: "es2015",
      sourcemap: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("./index.html", import.meta.url)
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: `static/js/[name]-[hash].${times}.js`,
          entryFileNames: `static/js/[name]-[hash].${times}.js`,
          assetFileNames: `static/[ext]/[name]-[hash].${times}.[ext]`
        }
      }
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    }
  };
};
